<template>
  <!-- 页面-应用管理 -->
  <div class="EmployeeOpenCard-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form :model="formSearch" ref="roleFormSearch" slot="adaption-bar" class="ivu-form-no-margin-bottom" inline>
        <template>

          <Form-item prop="tenantCode" label="租户编码">
            <Input type="text" v-model.trim="formSearch.tenantCode" :maxlength="30" @on-enter="search" />
          </Form-item>

          <Form-item prop="crCode" label="业务单元">
            <Input type="text" v-model.trim="formSearch.crCode" :maxlength="30" @on-enter="search" />
          </Form-item>

          <Form-item prop="userId" label="员工ID">
            <Input type="text" v-model.trim="formSearch.userId" :maxlength="30" @on-enter="search" />
          </Form-item>
          <Form-item prop="userName" label="员工姓名">
            <Input type="text" v-model.trim="formSearch.userName" :maxlength="30" @on-enter="search" />
          </Form-item>

        
          <Form-item prop="gender" label="性别">
          <Select
            placeholder="选择性别"
            v-model="formSearch.gender"
            transfer="true"
            class="no-borderColor"
            clearable
          >
            <Option value= 0 key="0"> 女 </Option>
            <Option value= 1  key="1"> 男 </Option>
          </Select>
        </Form-item>

        <Form-item prop="mobile" label="手机号">
            <Input type="text" v-model.trim="formSearch.mobile" :maxlength="30" @on-enter="search" />
          </Form-item>

        <Form-item prop="requestType" label="请求开卡方式">
          <Select
            placeholder="选择开卡方式"
            v-model="formSearch.requestType"
            transfer="true"
            class="no-borderColor"
            clearable
          >
            <Option value= 1 key="0"> 本地请求开卡 </Option>
            <Option value= 2  key="1"> 外部请求开卡 </Option>
          </Select>
        </Form-item>

        <Form-item prop="requestWay" label="请求方式">
          <Select
            placeholder="选择请求方式"
            v-model="formSearch.requestWay"
            transfer="true"
            class="no-borderColor"
            clearable
          >
            <Option value= 1 key="0"> 单条 </Option>
            <Option value= 2  key="1"> 多条 </Option>
          </Select>
        </Form-item>

        <Form-item prop="serviceType" label="操作类型">
          <Select
            placeholder="选择操作类型"
            v-model="formSearch.serviceType"
            transfer="true"
            class="no-borderColor"
            clearable
          >
            <Option value="A" key="0"> 开卡 </Option>
            <Option value= "I"  key="1"> 销卡 </Option>
          </Select>
        </Form-item>

        <Form-item prop="cardStatus" label="是否成功">
          <Select
            placeholder="选择是否成功"
            v-model="formSearch.cardStatus"
            transfer="true"
            class="no-borderColor"
            clearable
          >
            <Option value="Y" key="0"> 成功 </Option>
            <Option value= "N"  key="1"> 失败 </Option>
          </Select>
        </Form-item>



          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="formReset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <div class = "container">
      <div slot="table-bar">
      <RPButton optType="create" class="box-btn"  text="导出为Excel" @click="onExport" />
    </div>
      <div slot="table-bar">
      <RPButton optType="create" class="box-btn"  text="导入 Excel" style="margin-left: 150px;"  @click="selectFile" />
      <input type="file" ref="selectFile" style="display:none" @change="OnImport" />
      </div>
    
      <div slot="table-bar">
      <RPButton optType="create" class="box-btn"  text="导入模板下载"  @click="downLoadTemplete" />
       </div>
    </div>
   
 

          

    <InnerPageTable ref="appTable" :config="tableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="formReset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <!-- <RPButton optType="create" @click="edit()" /> -->
      </div>
       
    </InnerPageTable>
  </div>
</template>
<script>
import { deletApp, getTenantList } from '@/api/applicationApi.js'
import userCenter from '@/api/user.center.mixin'
import locales from './locales.js'
// import ApplicationEdit from "./AppEdit.vue";
// import AppSetting from "./AppSetting.vue";
// import appConfig from "./appConfig.vue"
import { CoreModuleName } from '@/const.js'
import tenantAPI from '@/api/tenantApi.js'
// import valueSetAPI from "@/api/valueSetAPI.js";
const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
export default {
  name: 'application-list',
  mixins: [userCenter, locales],
  data() {
    const { userInfo } = $store.state[CoreModuleName]
    return {
      useTableSearchBar: false,
      userRepositorys: {},
      editIconLoading: false,
      currTenantCode: userInfo.tenantCode || '', //租户编码
      currTenantName: '', //租户名称
      searchTenantList: [], //所属租户下拉框数据
      searchStatusList: [], //状态下拉框数据
      formSearch: {
        tenantCode:'',
        crCode:'',
        userId:'',
        userName:'',
        gender:'',
        mobile:'',
        requestType:'',
        requestWay:'',
        serviceType:'',
        cardStatus:''

      },
      searchTypeList: [
        {
          key: 'clientId',
          name: this.$t('module.appManage.appCode'),
          placeholder: this.$t('module.appManage.enterclientId')
        },
        {
          key: 'appName',
          name: this.$t('module.appManage.appNameGuess'),
          placeholder: this.$t('module.appManage.enterappName')
        }
      ],
      searchTypePlaceholder: this.$t('module.appManage.enterclientId')
      // category: 0
    }
  },
  
  computed: {
    tableConfig() {
      return { loadDataFn: this.getAppList, columnsFn: this.generateColumns,
        autoFirst: true, }
    }
  },
  created() {
    // const { userInfo } = $store.state[CoreModuleName];
    // this.category = userInfo.category;
    this.search()
     
  },
  methods: {
    OnImport(e){
      const inputCom = e.target;
      const files = inputCom.files;
      let param = new FormData();
      [].forEach.call(files, file => {
        if (!this.checkFileType(file.name.split(".").pop())) {
          this.$message.error({
            content: '文件扩展名有误',
            duration: 3
          });
          return false;
        } else {
          param.append("file", file);
        }
      });

      if (param.get("file")) {
        //添加请求头
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };

        this.showUploading();
        $http
          .post(this.concaturl_opencard('importCardLogExcel'),param,null, config)
          .then(response => {
            inputCom.value = "";
            this.$message.success({
              content: '导入成功',
              duration: 3
            });
            this.hideUploading();
          })
          .catch(() => {
            inputCom.value = "";
            this.hideUploading();
          });
      }

    },
    checkFileType: function(fileType) {
      const acceptTypes = ["xls", "xlsx"];
      for (var i = 0; i < acceptTypes.length; i++) {
        if (fileType === acceptTypes[i]) {
          return true;
        }
      }
    },
    hideUploading() {
      this.$Spin.hide();
    },
    showUploading() {
      this.$Spin.show({
        render: h => {
          return h("div", [
            h("Icon", {
              class: "demo-spin-icon-load",
              props: {
                type: "ios-loading",
                size: 18
              }
            }),
            h("div", this.$t("module.exportImport.uploading"))
          ]);
        }
      });
    },
    selectFile() {
      this.$refs.selectFile.click();
    },
    onExport(){
      let searchParams = Object.assign({}, this.formSearch)

      if (this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.formSearch.searchType == item.key) {
            searchParams[item.key] = this.formSearch.searchTypeValue
          } else {
            searchParams[item.key] = ''
          }
        })
      }
      delete searchParams.searchType
      delete searchParams.searchTypeValue

      if (searchParams.tenantCode == 'ALL') {
        searchParams.tenantCode = null
      }
      if (searchParams.enabled == 'ALL') {
        searchParams.enabled = null
      }
      console.log(searchParams);
      console.log(this.formSearch);
      Object.keys(searchParams).map(item=>{
        searchParams[item] == '' ? searchParams[item] = null:searchParams[item] ;
        
      })
      $http.post(this.concaturl_opencard('exportLogquery'),searchParams,null,{ responseType: "blob" })
            .then(response => {
              const fileInfo = response.headers["content-disposition"].split(";")[1];
              let fileName = decodeURIComponent(fileInfo && fileInfo.split("=")["1"]);
              let blob = new Blob([response.data]);
              let href = window.URL.createObjectURL(blob); //创建下载的链接
              if (window.navigator.msSaveBlob) {
                try {
                  window.navigator.msSaveBlob(blob, fileName);
                } catch (e) {
                  console.error(e);
                }
              } else {
                // 谷歌浏览器 创建a标签 添加download属性下载
                let downloadElement = document.createElement("a");
                downloadElement.href = href;
                downloadElement.target = "_blank";
                downloadElement.download = fileName; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象
              }
          });
    },
    downLoadTemplete(){
      $http.get(this.concaturl_opencard('downloadLogTemplate'),null,null,{ responseType: "blob" })
            .then(response => {
              const fileInfo = response.headers["content-disposition"].split(";")[1];
              let fileName = decodeURIComponent(fileInfo && fileInfo.split("=")["1"]);
              let blob = new Blob([response.data]);
              let href = window.URL.createObjectURL(blob); //创建下载的链接
              if (window.navigator.msSaveBlob) {
                try {
                  window.navigator.msSaveBlob(blob, fileName);
                } catch (e) {
                  console.error(e);
                }
              } else {
                // 谷歌浏览器 创建a标签 添加download属性下载
                let downloadElement = document.createElement("a");
                downloadElement.href = href;
                downloadElement.target = "_blank";
                downloadElement.download = fileName; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象
              }
          });
    },
    getAppList({ responseProcess, param }) {
     return $http.post(this.concaturl_opencard('queryOpenCardLogPage'), param).then(res => {
      res.data.data.pageNum = res.data.data.current;
      console.log(res)
         responseProcess(res.data.data)
    })
    },
    concaturl_opencard(url) {
       return window.RPConfig.mgt.concat(`/sysOpenCard/${url}`);
    },
    searchTypeChange() {
      if (this.formSearch.searchTypeValue) {
        this.search()
      }
    },
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant() {
      //   tenantAPI.queryAllTenantList().then(data => {
      //     for (const tenant of data) {
      //       if (this.currTenantCode == tenant.tenantCode) {
      //         this.currTenantName = tenant.tenantName;
      //       }
      //     }
      //   });
    },
    // //初始化所有 所属租户、状态（选择器列表）
    // async getselectorList() {
    //   const [searchTenantList, searchStatusList] = await Promise.all([
    //     getTenantList(),
    //     valueSetAPI.getValueSetByCode("ENABLED_CODE")
    //   ]);
    //   this.searchTenantList = searchTenantList.data;
    //   this.searchStatusList = searchStatusList;
    // },
    //初始化所有 所属租户（选择器列表）
    getselectorList() {
      //   getTenantList().then(res => {
      //     this.searchTenantList = res.data.map(item => {
      //       return {
      //         vsiKey: item.vsiKey,
      //         vsiValue: item.vsiValue
      //       };
      //     });
      //   });
    },
    generateColumns() {
      return [
        {
          title: '租户编码',
          align: 'center', 
          width: 110,
          key: "tenantCode"
        },
        {
          title: '业务单元',
          align: 'center', 
          width: 110,
          key: "crCode"
        },
        {
          title: '员工ID',
          align: 'center', 
          width: 110,
          key: "userId"
        },
        {
          title: '员工姓名', // 状态
          align: "center",
          width: 110,
          key: "userName"
          
        },
        {
          title: '性别',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let v = params.row.gender;
            let label = v == null? '未知':v == 0? '女':'男';
            return h(
              "span",    
              label
            );
          }
        },
        {
          title: '手机号',
          align: 'center',
          width: 110,
          key: "mobile"
        },
        {
          title: '请求开卡方式',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let v = params.row.requestType;
            let label = v == null? '未知':v == 1? '本地请求开卡':'外部请求开卡';
            return h('span', label);
          }
        },
        {
          title: '请求方式',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let v = params.row.requestWay;
            let label = v == null? '未知':v == 1? '单条':'多条';
            return h('span', label);
          }
        },
        {
          title: '操作类型',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let v = params.row.serviceType;
            let label = v == null? '未知':v == 'A'? '开卡':'销卡';
            return h('span', label);
          }
        },
        {
          title: '是否成功',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let v = params.row.cardStatus;
            let label = v == null? '未知':v == 'Y'? '成功':'失败';
            return h('span', label);
          }
        },
        {
          title: '原始报文',
          align: 'center',
          width: 110,
          key: "rawMessage"
        },
        {
          title: '异常信息',
          align: 'center',
          width: 110,
          key: "errorMessage"
        },
        {
          title: 'ssdp请求日志id',
          align: 'center',
          width: 170,
          key: "ecsbLogId"
        },
        {
          title: '创建人',
          align: 'center',
          width: 110,
          key: "createUser"
        },
        {
          title: '创建时间',
          align: 'center',
          width: 150,
          key: "createTime"
        },
        {
          title: '更新时间',
          align: 'center',
          width: 150,
          key: "updateTime"
        },
        {
          title: '更新人',
          align: 'center',
          width: 110,
          key: "updateUser"
        }
      ]
    },
    getOperatingCols(row) {
      let operatingCols = []
      // let tenants = this.$store.state[CoreModuleName].userInfo.tenantCode;
      if (this.currTenantCode == row.tenantCode || row.tenantCode == '') {
        // operatingCols.push({
        //   type: "icon",
        //   icon: "md-create",
        //   text: this.$t("common.edit"),
        //   // hidden: this.category != 1,
        //   handle: () => {
        //     this.edit(row.id,row);
        //   }
        // });
        operatingCols.push({
          type: 'icon',
          icon: 'ios-settings',
          text: this.$t('module.appManage.appSetting'),
          // hidden: this.category != 1,
          handle: () => {
            this.appSetting(row.id, row)
          }
        })
        operatingCols.push({
          type: 'icon',
          icon: 'ios-apps',
          text: this.$t('module.appManage.appConfig'),
          handle: () => {
            this.appConfig(row)
          }
        })
        operatingCols.push({
          type: 'icon',
          icon: 'ios-trash',
          text: this.$t('common.delete'),
          hidden: row.enabled == 1 ? true : false,
          handle: () => {
            this.deleted(row)
          }
        })
      } else {
        operatingCols.push({
          type: 'icon',
          icon: 'ios-eye',
          text: this.$t('common.detail'),
          // hidden: this.category == 1,
          handle: () => {
            this.detail(row.id)
          }
        })
      }

      return operatingCols
    },
    async initData() {
      //   userCenter mixins
      let userCenterList = await this.getUserCenterListData()

      this.search()
    },
    getIndex(index) {
      let num = this.$refs.appTable.currentPage < 1 ? 1 : this.$refs.appTable.currentPage
      return (num - 1) * this.$refs.appTable.param.pageSize + index + 1
    },
    getUserCenterName(id) {
      return this.userRepositorys[id] || id
    },
    search(page = 1) {
      // this.$refs["appTable"].load(Object.assign({}, this.formSearch), page);
      let searchParams = Object.assign({}, this.formSearch)

      if (this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.formSearch.searchType == item.key) {
            searchParams[item.key] = this.formSearch.searchTypeValue
          } else {
            searchParams[item.key] = ''
          }
        })
      }
      delete searchParams.searchType
      delete searchParams.searchTypeValue

      if (searchParams.tenantCode == 'ALL') {
        searchParams.tenantCode = null
      }
      if (searchParams.enabled == 'ALL') {
        searchParams.enabled = null
      }
      Object.keys(searchParams).map(item=>{
        searchParams[item] == '' ? searchParams[item] = null:'';

      })
      this.$refs['appTable'].load(searchParams, page)
    },
    appSetting(id, row) {
      new this.$pageModal(
        AppSetting,
        {
          props: {
            appInfo: {
              id: id,
              clientId: row.clientId,
              tenantCode: row.tenantCode
            },
            tenantName: this.currTenantName,
            row
            // tenantName: this.$store.state[CoreModuleName].userInfo.tenantCode
          }
        },
        data => {
          this.getselectorList()
          if (data) {
            this.search(this.$refs.appTable.param.pageNum)
            this.$store.commit(CoreModuleName + '/clearAllCache')
          }
        }
      )
    },
    // 应用配置弹框
    appConfig(row) {
      //   new this.$pageModal(
      //     appConfig,
      //     {
      //       props: {
      //         appInfo: {
      //           id: row.id,
      //           clientId: row.clientId,
      //           tenantCode: row.tenantCode
      //         },
      //         row
      //       }
      //     },
      //     data => {
      //       // this.getselectorList()
      //       if (data) {
      //         this.search(this.$refs.appTable.param.pageNum);
      //         this.$store.commit(CoreModuleName + "/clearAllCache");
      //       }
      //     }
      //   );
    },
    detail(id) {
      new this.$pageModal(
        ApplicationEdit,
        {
          props: {
            appInfo: {
              id: id
            },
            tenantName: this.currTenantName,
            readOnly: true
            // tenantName: this.$store.state[CoreModuleName].userInfo.tenantCode
          }
        },
        data => {}
      )
    },
    deleted(row) {
      // // deleteAppFlag:1-可以删除应用（应用没有分配给任何租户）；0-不能删除应用（应用已关联租户）
      // if (row.deleteAppFlag == 0 && row.enabled == 0) {
      //   this.$message.error({
      //     content: this.$t("module.appManage.warning.deleteError"),
      //     duration: 3
      //   });
      //   return;
      // }
      if (row.enabled == 1) {
        this.$message.error({
          content: this.$t('module.appManage.warning.deleteError'),
          duration: 3
        })
        return
      }
      // 删除提示级别：严重
      new $confirm(this.$t('module.appManage.warning.confirmToDelete'), this).then(() => {
        deletApp(row.id).then(() => {
          this.$message.success({
            content: this.$t('common.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
      })
    },
    formReset() {
      this.$refs['roleFormSearch'].resetFields()
      this.search()
    }
  },
  watch: {
    'formSearch.searchType': {
      handler() {
        let selectItem = this.searchTypeList.find(item => item.key == this.formSearch.searchType)
        this.searchTypePlaceholder = selectItem ? selectItem.placeholder : ''
      }
    }
  }
}
</script>
<style lang="less">
// ok注释的样式
.EmployeeOpenCard-page {
  .ivu-form-item {
    .ivu-form-item-label {
      line-height: 14px !important;
    }
  }
}
.box-btn{
  float:left;
  margin-left: 15px;  /* 左边间距 */
  margin-right: 15px; /* 右边间距 */
}


</style>
<style lang="less">
// .ApplicationList-page {
//   .core-modal {
//     width: 774px!important;
//   }
// }
</style>
